package it.tcm.TeacherClassMate.servlet;

import it.tcm.TeacherClassMate.beans.MailBean;
import it.tcm.TeacherClassMate.facade.MailManageBase;
import it.tcm.TeacherClassMate.util.SendMail;

import java.io.File;
import java.util.TimerTask;

import org.apache.log4j.Logger;

public class MyTimerTask extends TimerTask {
	
	private Logger logger = Logger.getLogger(this.getClass().getName());
	
	public void run() {
		
		// checking and getting one mail of type 1
		MailManageBase mmb = new MailManageBase();
		//logger.info("my timer task");
		MailBean mailgetted = null;
		try  {
			mailgetted = mmb.getFirstMailByNoSentAndNoLockType1();
			//logger.info("mailgettedtype1 " + mailgetted);
			if (mailgetted != null) {
				mailgetted.setLock("1");
				mmb.save(mailgetted);
				SendMail.sendMailAndUpdate(mailgetted);
				logger.info("mail id getted " + mailgetted.getId() + " and sended");
			}
		} catch (Exception e) {
			if (mailgetted != null) {
				mailgetted.setLock("0");
				mmb.save(mailgetted);
			}
		}
		
		// checking and getting one mail of type 2
		try  {
			mailgetted = mmb.getFirstMailByNoSentAndNoLockType2();
			//logger.info("mailgettedtype2 " + mailgetted);
			if (mailgetted != null) {
				mailgetted.setLock("1");
				mmb.save(mailgetted);
				SendMail.sendMailWithAttachAndUpdate(mailgetted);
				logger.info("mail with attach with id getted " + mailgetted.getId() + " and sended");
				// delete file
				File file = new File(mailgetted.getFile());
				file.delete();
			}
		} catch (Exception e) {
			if (mailgetted != null) {
				mailgetted.setFailed(mailgetted.getFailed() + 1);
				mailgetted.setLock("0");
				mmb.save(mailgetted);
				logger.info("exception while sending " + mailgetted.getId() + " and failed = " + mailgetted.getFailed());
				logger.error(e.getMessage());
				logger.error(e);
			}
	
		}
		
		
	}

}
